package com.atguigu.flink.chapter11;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/22 10:35
 */
public class Flink01_Table_BaseUse {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        // 1. 表的执行环境
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        // 2. 通过执行环境, 把流转成动态表
        // 表一定有列: 默认情况表的列和pojo的属性一致
        Table table = tEnv.fromDataStream(waterSensorStream);
        // 3. 在动态表上执行连续查询, 得到新的动态表
        // select * from t where id='sensor_1'
        /*Table result = table
            .where("id='sensor_1'")
            .select("id,ts,vc");*/
    
        Table result = table
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("vc"));
        // 4. 把动态表转成流, 打印
//        DataStream<WaterSensor> stream = tEnv.toAppendStream(result, WaterSensor.class); // 动态只有新增, 则使用这个
//        DataStream<Row> stream = tEnv.toAppendStream(result, Row.class);
//        stream.print();
        result.execute().print();
    
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
